
(function (jQuery){
    this.alerts = function (message,title,modal,type,callback){
        type = (type || 'error');
        title = (title || '错误信息');
        modal = (modal || true);
	    var id = 'dushijia_dialog_'+type;
	    callback = definefunc(callback) || function(){};
        var dialogid = $('#'+id);
        var message = '<div class="messager-icon messager-'+type+'"></div><p class="dushijia_'+type+' nbr">'+message+'</p>';
    	
        var buttons = { "确定": function() { callback(dialogid) ? dialogid.dialog("destroy").remove() : dialogid.dialog("close");return true; } };
        if (dialogid.length){
        	dialogid.html(message);
        	dialogid.dialog('option','buttons',buttons);
    		return dialogid.dialog('open');
    	}
        dialogid = $("<div id='"+id+"'/>").html(message);
	    dialogid.dialog({
    		bgiframe: true,
    		closeOnEscape:false,
    		height:'auto',
    		resizable:false,
    		modal: modal,
    		title:title,
    		buttons: buttons
    		/*帮助button加入样式
    		open: function() {
            $('.ui-dialog-buttonpane').find('button:contains("确定")').addClass('cancelButtonClass');
        	}*/
    	});
	    $('.ui-dialog-buttonpane').find('button:contains("确定")').focus();
    	return dialogid;
    };
    
    this.close = function (type){
	    var id = 'dushijia_dialog_'+type;
        var dialogid = $('#'+id);
	    dialogid.dialog("destroy").remove();
    	return dialogid;
    };
    
    this.error = function (message,title,modal){
    	title = (title || '错误信息');
    	this.alerts(message,title,modal,'error');
    	window.setTimeout(function(){
    		this.close('error');
		}, 1500);
    };
    
    this.success = function (message,title,modal){
    	title = (title || '正确信息');
    	this.alerts(message,title,modal,'success');
    };
    
    this.info = function (message,title,modal){
    	title = (title || '提示信息');
    	this.alerts(message,title,modal,'info');
    	window.setTimeout(function(){
    		this.close('info');
		}, 1500);
    };
    
    this.warning = function (message,title,modal){
    	title = (title || '警告信息');
    	this.error(message,title,modal,'warning');
    	window.setTimeout(function(){
    		this.close('warning');
		}, 1500);
    };
    
    
    
    this.fromhtml = function (message,title,modal,type,callback){
        type = (type || 'error');
        title = (title || '错误信息');
        modal = (modal || true);
	    var id = 'dushijia_dialog_'+type;
	    callback = definefunc(callback) || function(){};
        var dialogid = $('#'+id);
        var message = '<div class="messager-icon messager-'+type+'"></div><p class="dushijia_'+type+' nbr">'+message+'</p>';
    	
        var buttons = { "确定": function() { callback(dialogid) ? dialogid.dialog("destroy").remove() : dialogid.dialog("close");return true; } };
        if (dialogid.length){
        	dialogid.html(message);
        	dialogid.dialog('option','buttons',buttons);
    		return dialogid.dialog('open');
    	}
        dialogid = $("<div id='"+id+"'/>").html(message);
	    dialogid.dialog({
    		bgiframe: true,
    		closeOnEscape:false,
    		height:'auto',
    		resizable:false,
    		modal: modal,
    		title:title
    		/*帮助button加入样式
    		open: function() {
            $('.ui-dialog-buttonpane').find('button:contains("确定")').addClass('cancelButtonClass');
        	}*/
    	});
	    $('.ui-dialog-buttonpane').find('button:contains("确定")').focus();
    	return dialogid;
    };
    
    this.forms = function (message,title,modal){
    	title = (title || '填写信息');
    	this.fromhtml(message,title,modal,'info');
    };

    
    this.confirm = function (message,callback_ok,callback_cancel,modal,title){
        var type = 'confirm';
        var title = (title || '确认信息');
        var modal = (modal || false);
        var id = 'dushijia_dialog_'+type;
	    var message = '<div class="messager-icon messager-'+type+'"></div><p class="dushijia_'+type+' nbr">'+message+'</p>';
        
	    callback_ok = definefunc(callback_ok) || function(){};
	    callback_cancel = definefunc(callback_cancel) || function(){};
	    var buttons = {
                '确定':function() {callback_ok(dialogid); dialogid.dialog("destroy").remove(); return true; },
                '取消':function() {callback_cancel(dialogid); dialogid.dialog("destroy").remove(); return false;}
        };
	    
    	var dialogid = $("<div id='dushijia_"+type+"'/>").html(message);
    	dialogid.dialog({
    		bgiframe: true,
    		closeOnEscape:false,
    		modal: true,
    		title:title,
    		resizable:false,
    		close:function(){
    			dialogid.dialog("destroy").remove();
    		},
    		buttons: buttons,
    		open: function() {
            $('.ui-dialog-buttonpane').find('button:contains("确定")').addClass('cancelButtonClass');
        	}
    	});
    	$('.ui-dialog-buttonpane').find('button:contains("确定")').focus();
    	return dialogid;
    };
   
    this.iframe = function(url,width,height,callback_onload,callbacks)
    {
        width || (width = 450);
        height || (height = 386);
        if (/(\d+)%/.test(width))
        {
        	width = (parseInt(RegExp.$1)/100) * mumayi.innerWidth();
        }
        if (/(\d+)%/.test(height))
        {
        	height = (parseInt(RegExp.$1)/100) * mumayi.innerHeight();
        }
        var iframe = $('<iframe frameborder="0" scrolling="auto" src="'+url+'" width="100%" height="100%" ></iframe>');
        
        var dialog = $('<div/>').html(iframe);
		var masker = $('<div style="background:#44DAF4;z-index:1;position:absolute;display:none;width:100%;height:100%"/>')
					.css('opacity',.4);
        dialog.dialog({
			bgiframe: true,
			width : width,
			height: height,
			modal: true,
			title:ct.substr(url,30),
    		close:function(){
    			iframe.data('bindclose')
    			  ? iframe.trigger('close')
    			  : dialog.dialog("destroy").remove();
    		}
		});
		masker.insertBefore(iframe);
		
        
		var showMasker = function(){
		    masker.show();
		    $(document).mouseup(hideMasker);
		};
		var hideMasker = function(){
		    $(document).unbind('mouseup',hideMasker);
		    masker.hide();
		};
		var span = dialog.prev('h2').mousedown(showMasker).children('span:first');
		dialog.nextAll('.ui-resizable-handle').mousedown(showMasker);
		dialog.css('overflow','hidden');
		iframe.bind('load', function(){
		    try {
				var doc = this.contentDocument || this.contentWindow.document;
				var w = (this.contentWindow || this);
				if (!iframe.data('bindclose'))
				{
					iframe.bind('close',function(){
	    			    iframe.unbind().bind('load', function(){
	    			    	dialog.dialog("destroy").remove();
	    			    });
						w.location = "about:blank";
					});
					iframe.data('bindclose',1);
				}
				w.getDialog = function(){
				    return dialog;
				};
				callbacks && (w.dialogCallback = callbacks);
				if (doc.title && doc.title.length) {
					span.text(ct.substr(doc.title,50));
				} else {
					throw "no title";
				}
			}
			catch (e) {
			    span.text(ct.substr(this.src,50));
			}
			(callback_onload = definefunc(callback_onload)) && callback_onload(iframe);
		});
		return dialog;
    },
    this.ajax =function(title, url, width, height, callback_onload, callback_ok, callback_cancel)
    {
        width  || (width = 450);
        height || (height = 386);
        if (/(\d+)%/.test(width))
        {
        	width = (parseInt(RegExp.$1)/100) * mumayi.innerWidth();
        }
        if (/(\d+)%/.test(height))
        {
        	height = (parseInt(RegExp.$1)/100) * mumayi.innerHeight();
        }
        var dialog = $('<div/>');
        
        var buttons = {};
        (callback_ok = definefunc(callback_ok)) && (buttons['确定'] = function() { callback_ok(dialog) && dialog.dialog("destroy").remove(); return true; })
        && (
            (callback_cancel = definefunc(callback_cancel))
            && (buttons['取消'] = function() { callback_cancel(dialog) && dialog.dialog("destroy").remove(); return false; })
        );
        callback_onload = definefunc(callback_onload);
        dialog.dialog({
            autoOpen:false,
			bgiframe: true,
			width : width,
			height: height,
			modal : true,
			title : title,
			buttons : buttons,
    		open: function() {
            $('.ui-dialog-buttonpane').find('button:contains("确定")').addClass('submitButtonClass');
        	},
    		close:function(){
    		    dialog.dialog("destroy").remove();
    		}
		}).load(url,function(){
		    dialog.dialog('open');
        	callback_onload && callback_onload(dialog);
        }).bind('ajaxload',function(){
            callback_onload && callback_onload(dialog);
        });
        return dialog;
    },
    /**
     * need plugin jquery.form.js & mumayi.validator.js to support
     */
    this.form =function(title, url, width, height, callback_submit_result, callback_form_ready, callback_before_submit)
    {
        var form = null;
        var callback_onload = function(dialog)
        {
            form = $('form:eq(0)',dialog);
            if (form.length)
            {
                // create masker
                var masker = $('<div style="background:#44DAF4;z-index:2;position:absolute;display:none;width:100%;height:100%"/>')
                              .css('opacity',.4);
                dialog.prepend(masker);
                var buttons = dialog.nextAll('div.btn_area').children('button');
                (callback_form_ready = definefunc(callback_form_ready))
                    && callback_form_ready(form, dialog);
                    
                var submitHandler = function(){
                    form.ajaxSubmit({
                        dataType:  'json',
                		type:'post',
                		success: function(json)
                		{
                		    var info = null;
                		    json.status === undefined &&
                		        (info = $('<div class="warning"><sub></sub>'
										+($.isArray(json.message) ? json.message.join('<br/>') : json.message)
										+'</div>')) ||
                		    !json.status &&
                		        (info = $('<div class="error"><sub></sub>'
										+json.message+'</div>')) ||
                		    json.message &&
                		        (info = $('<div class="success"><sub></sub>'
										+json.message+'</div>'));
							info && (dialog.prepend(info),setTimeout(function(){info && info.hide()},2000));
							
							(callback_submit_result = definefunc(callback_submit_result))
							? (
							    callback_submit_result(json)
							    // close dialog
                			    ? dialog.dialog('destroy').remove()
                			    // hide masker
                			    : (masker.hide(), buttons.removeAttr('disabled'))
							) : (
							    json.status
							    // close dialog
                			    ? dialog.dialog('destroy').remove()
                			    // hide masker
                			    : (masker.hide(), buttons.removeAttr('disabled'))
							);
                			
                			return false;
                		},
                		beforeSubmit:function()
                		{
                		    // show masker
                		    //masker.show();
                		    (callback_before_submit = definefunc(callback_before_submit))
                		      && callback_before_submit(frm);
							// disabled butttons
							buttons.attr('disabled','disabled');
                		    return true;
                		}
                    });
                }
                if (form[0].getAttribute('name')) {
                    form.validate({
                        submitHandler:submitHandler
                    });
                } else {
                	$(form[0].elements)
                	  .not(':button,:submit,:image,:reset,:hidden,[disabled],[readonly]')
                	  .eq(0).focus();
                	form.submit(function(e){
                        submitHandler(form);
                        return false;
                    });
                }
            }
        };
        var callback_ok = function(dialog)
        {
			form && form.submit();
            return false;
        };
        var callback_cancel = function(){ return true; }
        
        return this.ajax(title, url, width, height, callback_onload, callback_ok, callback_cancel);
    };
    
    
    function  definefunc(ns, context) {
        if (typeof ns == 'function') {
            return ns;
        }
        if (typeof ns == 'string') {
            ns = ns.split('.');
            var o = (context || window)[ns[0]], w = null;
            if (!o) return null;
            for (var i=1,l;l=ns[i++];) {
                if (!o[l]) {
                    return null;
                }
                w = o;
                o = o[l];
            }
            return o && (function(){
                return o.apply(w, arguments);
            });
        }
        return null;
    };
   
    jQuery.dialog = this;
    return jQuery;
})(jQuery);







